<?php
/*
 * @Description    : 
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2020-02-08 15:01:43
 * @LastEditors    : QianLong
 * @LastEditTime   : 2024-02-22 15:31:21
 */

declare(strict_types=1);

namespace App\Controller;

use App\Constants\Status;
use App\Exception\ApiException;
use Qianlong\Validate\Validate;

class AdsApiController extends AbstractController
{
  public function getAdsList()
  {
    $valitor = new Validate();
    $valitor->addColumn('c_id')->required();
    $valitor->addColumn('page_size')->optional();
    $valitor->addColumn('page')->optional();
    if ($valitor && !$this->validate($valitor)) {
      throw new ApiException(Status::CODE_BAD_REQUEST, $valitor->getError()->__toString());
    }
    unset($valitor);
    $param = $this->request->all();
    $param['page_size'] = (!isset($param['page_size']) || empty($param['page_size']))?10: (int)$param['page_size'];
    $param['page'] = (!isset($param['page']) || empty($param['page']))?1: (int)$param['page'];
    $cateInfo = $this->redisCache->getAdsCate($param['c_id']);
    $time = time();
    $where['status'] = 1;
    $where['start_time'] = ['$lte' => $time];
    $where['end_time'] = ['$gte' => $time];
    $where['cate_id_var'] = ['$elemMatch' => ['$eq' => $param['c_id']]];
    $skip = ($param['page'] - 1)*$param['page_size'];
    $list = mongodb2()->web_ads_list->find($where, ['limit' => (int)$param['page_size'],'skip' => (int)$skip, 'sort' => ['sort' => -1]]);
    unset($where,$param,$skip,$time);
    if ($list) {
      $newList = [];
      foreach ($list as $key => $vo) {
        $newList[$key]['width'] = $cateInfo['width'];
        $newList[$key]['height'] = $cateInfo['height'];
        $newList[$key]['_id'] = $vo['_id'];
        $newList[$key]['title'] = $vo['title'];
        $newList[$key]['type'] = isset($vo['type'])? $vo['type']:'';
        $newList[$key]['url_text'] = isset($vo['url_text'])? $vo['url_text']:'';
        $newList[$key]['html'] = isset($vo['html'])? $vo['html']:'';
        // $newList[$key]['original_url'] = $vo['url'];
        if (isset($vo['use_url']) && $vo['use_url'] == '0') {
          $newList[$key]['url'] = $vo['url'];
        }else{
          $newList[$key]['url'] = 'https://21ds.cn/clickAds/' . $vo['_id'];
        }
        $newList[$key]['pic'] = $vo['pic'];
        $newList[$key]['pic2'] = !isset($vo['pic2'])?'': $vo['pic2'];
        $newList[$key]['pic_bg_color'] = !isset($vo['pic_bg_color'])?'': $vo['pic_bg_color'];
        $newList[$key]['dzParam'] = !isset($vo['dzParam'])?[]: $vo['dzParam'];
      }
      return $this->response->json(Status::CODE_OK, 'success', $newList);
    } else {
      return $this->response->json(Status::CODE_FAIL, '无可用广告');
    }
  }
}
